package com.yunshang.shoppingmall.service.impl;

import com.yunshang.shoppingmall.common.ExcelUtil;
import com.yunshang.shoppingmall.entity.*;
import com.yunshang.shoppingmall.service.*;
import com.yunshang.shoppingmall.service.User.UserRankService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service("exportService")
public class ExportServiceImpl implements ExportService {
    private static final int  BUFFER_SIZE = 2 * 1024;
    @Autowired
    ConfigService configService;
    @Autowired
    UserRankService userRankService;
    @Autowired
    CartService cartService;
    @Autowired
    ExportOrderService exportOrderService;
    @Autowired
    OrderExportService orderExportService;
    @Autowired
    DemolitionOrderService demolitionOrderService;
    @Autowired
    AddressService addressService;
    @Autowired
    OrderService orderService;
    @Autowired
    ExportService exportService;
    @Override
    public List<RemoveUserAndAddress> removeDuplicate(List<RemoveUserAndAddress> list) {
        List<RemoveUserAndAddress> distinctClass = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getUserId() + ";" + o.getPhone()+ ";" + o.getLogname()+ ";" + o.getAddressAll()))), ArrayList::new));//+ ";" + o.getAddressId()
        return distinctClass;
    }

    @Override
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public OrderExport orderGroup(OrderExport orderExport) {
        OrderExport orderExportTemp = new OrderExport();
        orderExportTemp.setLogname(orderExport.getLogname());
        orderExportTemp.setPhone(orderExport.getPhone());
        orderExportTemp.setGuigeName(orderExport.getGuigeName());
        orderExportTemp.setGuigeName1(orderExport.getGuigeName1());
        orderExportTemp.setAddressAll(orderExport.getAddressAll());
        orderExportTemp.setProductCount(orderExport.getProductCount());
        orderExportTemp.setProvincename(orderExport.getProvincename());
        orderExportTemp.setCityname(orderExport.getCityname());
        orderExportTemp.setAreaname(orderExport.getAreaname());
        orderExportTemp.setDetailAddr(orderExport.getDetailAddr());
        orderExportTemp.setProWeight(orderExport.getProWeight());
        orderExportTemp.setOrderNo(orderExport.getOrderNo());
        orderExportTemp.setSupplier(orderExport.getSupplier());
        return orderExportTemp;
    }

    @Override
    public List<OrderExport> assOrderData(List<OrderExport> list2) {
        Config userConfig= configService.selectByPrimaryKey(1);
        List<OrderExport> listTemp1=new ArrayList<>();
        OrderExport orderExport=new OrderExport();
        String names="",orderNos="";double weight=0.0;int c=0;
        Set<String> set = new HashSet();
        for (int i=0;i<list2.size();++i){
            OrderExport orderExport1=list2.get(i);
            orderExport=orderExport1;
            //判断重量是否是大于5公斤
            double weightdouble=0.0;
            int productCount=0;
            try {
                weightdouble= Double.parseDouble(orderExport1.getProWeight().toString());
                productCount=orderExport1.getProductCount();
            }catch (Exception E){

            }
            weight += weightdouble * productCount;
            if (weight > userConfig.getWeight()) {
                OrderExport orderExportTemp = orderGroup(orderExport1);
                orderExportTemp.setGuigeName(names);
                orderExportTemp.setGuigeName1(orderExport1.getGuigeName1());
                orderExportTemp.setProWeight(weightdouble);
                orderExportTemp.setOrderNo(orderExport1.getOrderNo());
                listTemp1.add(orderExportTemp);
                //System.out.println("a1:"+orderExportTemp.toString());
                names = "";weight = 0;c = 0;
                names += orderExport1.getGuigeName();
                weight += weightdouble * productCount;
                c++;
            } else {
                if (i == list2.size()-1- c) {
                    names += orderExport1.getGuigeName();
                    orderNos +=orderExport1.getOrderNo();
                    set.add(orderExport1.getOrderNo());
                } else {
                    set.add(orderExport1.getOrderNo());
                    orderNos +=orderExport1.getOrderNo()+",";
                    names += orderExport1.getGuigeName() + "+";
                }
            }
            c++;
        }
        String nos="";
        List<String> list_1 = new ArrayList<>(set);
        for (int i = 0; i <list_1.size() ; i++) {
            if(i==(list_1.size()-1)){
                nos +=list_1.get(i);
            }else {
                nos +=list_1.get(i)+",";
            }
        }
        int len=names.length();
        if(len>0){
            if(names.substring(len-1, len).equals("+")){
                names=names.substring(0, len -1);
            }
        }
        orderExport.setGuigeName(names);
        orderExport.setOrderNo(nos);
        listTemp1.add(orderExport);
        return listTemp1;
    }

    @Override
    public List<OrderExport> assOrderDataName(List<OrderExport> list2,String name) {
        Config userConfig= configService.selectByPrimaryKey(1);
        List<OrderExport> listTemp1=new ArrayList<>();
        OrderExport orderExport=new OrderExport();
        String names="",orderNos="";double weight=0.0;int c=0;
        Set<String> set = new HashSet();
        for (int i=0;i<list2.size();++i){
            OrderExport orderExport1=list2.get(i);
            String orderNo=orderExport1.getOrderNo()==null?"":orderExport1.getOrderNo();
            String supName=orderExport1.getSupplier()==null?"":orderExport1.getSupplier();
            //System.out.println("supNameSS:"+supName);
            if(supName.equals(name)&&!"".equals(orderNo)){
                orderExport=orderExport1;
                //判断重量是否是大于5公斤
                double weightdouble=0.0;
                int productCount=0;
                try {
                    weightdouble= Double.parseDouble(orderExport1.getProWeight().toString());
                    productCount=orderExport1.getProductCount();
                }catch (Exception E){

                }
                weight += weightdouble * productCount;
                if (weight > userConfig.getWeight()) {
                    OrderExport orderExportTemp = orderGroup(orderExport1);
                    orderExportTemp.setGuigeName(names);
                    orderExportTemp.setGuigeName1(orderExport1.getGuigeName1());
                    orderExportTemp.setProWeight(weightdouble);
                    orderExportTemp.setOrderNo(orderExport1.getOrderNo());
                    orderExportTemp.setSupplier(orderExport1.getSupplier());
                    listTemp1.add(orderExportTemp);
                    //System.out.println("a1:"+orderExportTemp.toString());
                    names = "";weight = 0;c = 0;
                    names += orderExport1.getGuigeName();
                    weight += weightdouble * productCount;
                    c++;
                } else {
                    if (i == list2.size()-1- c) {
                        names += orderExport1.getGuigeName();
                        orderNos +=orderExport1.getOrderNo();
                        set.add(orderExport1.getOrderNo());
                    } else {
                        set.add(orderExport1.getOrderNo());
                        orderNos +=orderExport1.getOrderNo()+",";
                        names += orderExport1.getGuigeName() + "+";
                    }
                }
                c++;
            }
        }
        String nos="";
        List<String> list_1 = new ArrayList<>(set);
        for (int i = 0; i <list_1.size() ; i++) {
            if(i==(list_1.size()-1)){
                nos +=list_1.get(i);
            }else {
                nos +=list_1.get(i)+",";
            }
        }
        int len=names.length();
        if(len>0){
            if(names.substring(len-1, len).equals("+")){
                names=names.substring(0, len -1);
            }
        }
        orderExport.setGuigeName(names);
        orderExport.setOrderNo(nos);
        listTemp1.add(orderExport);
        return listTemp1;
    }

    @Override
    public void toZip(List<File> srcFiles, OutputStream out) {
        /**
         * 压缩成ZIP 方法2
         * @param srcFiles 需要压缩的文件列表
         * @param out           压缩文件输出流
         * @throws RuntimeException 压缩失败会抛出运行时异常
         */
            long start = System.currentTimeMillis();
            ZipOutputStream zos = null ;
            try {
                zos = new ZipOutputStream(out);
                for (File srcFile : srcFiles) {
                    byte[] buf = new byte[BUFFER_SIZE];
                    zos.putNextEntry(new ZipEntry(srcFile.getName()));
                    int len;
                    FileInputStream in = new FileInputStream(srcFile);
                    while ((len = in.read(buf)) != -1){
                        zos.write(buf, 0, len);
                    }
                    zos.closeEntry();
                    in.close();
                }
                long end = System.currentTimeMillis();
                System.out.println("压缩完成，耗时：" + (end - start) +" ms");
            } catch (Exception e) {
                throw new RuntimeException("zip error from ZipUtils",e);
            }finally{
                if(zos != null){
                    try {
                        zos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        List<RemoveUserAndAddress> listOther=new ArrayList<>();//存放去重的用户收货信息
        List<OrderExport> listEx1 = orderExportService.getOrderExportData1();//
//        List<OrderExport> listEx2 = orderExportService.getOrderExportData2();//
//        listEx1.addAll(listEx2);
        List<OrderExport> list = listEx1;//导单数据
        List<OrderExport> listTemp=new ArrayList<>();//特殊产品
        List<OrderExport> listTempOther=new ArrayList<>();//特殊以外的其他产品数据
        List<OrderExport> listTempSupplier=new ArrayList<>();//供货商产品数据
        List<DemolitionOrder> demolitionOrders=demolitionOrderService.selectAll();//需要进行拆单的基础数据
        HashSet<String> hashSet=new HashSet<>();//订单编号
        int number=0;//导单数量
        int up=0;
        String[] title = {"业务单号","收件人姓名","收件人手机","收件人地址","品名","数量","备注","订单号"};
        String fileName = "物流导单"+System.currentTimeMillis()+".xls";
        DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        String busidstr = format2.format(new Date());
        String sheetName = "HSYS"+busidstr;
        OrderExport errorOO=new OrderExport();
        Set<String> listSupplier=new HashSet<>();
        String supName="";
        String suname="贵州荟生生物科技有限公司";
        try {
            for (int i = 0; i < list.size(); i++) {
                OrderExport orderExport = list.get(i);
                String supplier = orderExport.getSupplier() == null ? "" : orderExport.getSupplier();
                if ("".equals(supplier)) {
                    supName = "未知";
                } else {
                    supName = supplier;
                }
                if(!supName.equals(suname)){
                    listSupplier.add(supName);
                }
                errorOO = list.get(i);
                String[] strings = orderExport.getOrderNo().split(",");
                if (strings.length == 1) {
                    hashSet.add(orderExport.getOrderNo());
                } else {
                    for (String str : strings) {
                        hashSet.add(str);
                    }
                }
                //获取所有用户收货信息
                RemoveUserAndAddress orderExport1 = new RemoveUserAndAddress();
//                orderExport1.setUserId(orderExport.getUserId());
                orderExport1.setLogname(orderExport.getLogname());
                orderExport1.setPhone(orderExport.getPhone());
                orderExport1.setAddressAll(orderExport.getAddressAll());
                String name = list.get(i).getGuigeName1();
                //orderExport1.setAddressId(orderExport.getAddressId());
                listOther.add(orderExport1);
                //获取所有用户收货信息结束
                int productId = 0, guigeId = 0, productCount = 0;
                productId = list.get(i).getProductId();
                guigeId = list.get(i).getGuigeId();
                productCount = list.get(i).getProductCount();
                //判断产品大于一定数量是否拆单
                int finalProductId = productId;
                int finalGuigeId = guigeId;
                //判断产品大于一定数量是否拆单
                boolean isChai = demolitionOrders.stream().anyMatch(str -> (finalProductId == str.getProductid() && finalGuigeId == str.getGuigeid() && str.getType() == 1));
                boolean isChai1 = demolitionOrders.stream().anyMatch(str -> (finalProductId == str.getProductid() && finalGuigeId == str.getGuigeid() && str.getType() == 2));
                if (!suname.equals(supName)) {
                    listTempSupplier.add(orderExport);
                } else if (isChai) {//类型为1拆单
                    for (int n = 0; n < productCount; n++) {
                        OrderExport orderExportTemp = orderExport;
                        orderExportTemp.setGuigeName(name + "*" + 1);
                        listTemp.add(orderExportTemp);
                        number++;
                    }
                } else if (isChai1) {//类型为2拆单
                    int c = productCount / 6;// a-(a/b)*b
                    if (c == 1) {//单瓶整除为1
                        OrderExport orderExportTemp = exportService.orderGroup(orderExport);
                        orderExportTemp.setGuigeName(name + "*" + 6);
                        listTemp.add(orderExportTemp);
                        number++;
                    }
                    if (c > 1) {//单瓶整除大于1
                        for (int n = 0; n < c; n++) {
                            OrderExport orderExportTemp = exportService.orderGroup(orderExport);
                            orderExportTemp.setGuigeName(name + "*" + 6);
                            listTemp.add(orderExportTemp);
                            number++;
                        }
                    }
                    if (productCount % 6 != 0) {//处理剩下不到一件的
                        int d = productCount - (productCount / 6) * 6;
                        OrderExport orderExportTemp = exportService.orderGroup(orderExport);
                        orderExportTemp.setGuigeName(name + "*" + d);
                        listTemp.add(orderExportTemp);
                        number++;
                    }
                } else {
                    //添加到特殊产品拆单以外的其它集合
                    listTempOther.add(orderExport);
                }
            }
            //根据用户合并其它产品
            //去除用户重复的收货信息
            List<RemoveUserAndAddress> list1 = exportService.removeDuplicate(listOther);

            //根据去重的用户收货信息进行整合特殊以外产品信息
            List<OrderExport> listTempXX = new ArrayList<>();
            for (String str : listSupplier) {
                for (RemoveUserAndAddress item : list1) {
                    List<OrderExport> list2 = listTempSupplier.stream().filter(c -> (
                            c.getLogname() != null && c.getLogname().equals(item.getLogname()) &&
                                    c.getPhone() != null && c.getPhone().equals(item.getPhone()) &&
                                    c.getAddressAll() != null && c.getAddressAll().equals(item.getAddressAll()))
                    ).collect(Collectors.toList());
                    Collections.sort(list2, Comparator.comparingInt(OrderExport::getProductCount));//根据数量排序
                    if (list2 != null && list2.size() > 0) {
                        listTempXX = exportService.assOrderDataName(list2,str);
                    }
                    if (list2 != null && list2.size() > 0) {
                        if(listTempXX!=null&&listTempXX.size()>0){
                            List<OrderExport> list1q=listTempXX.stream().filter(c -> (!c.getOrderNo().equals("null")&&!c.getOrderNo().equals("")))
                                    .collect(Collectors.toList());
                            listTempXX=list1q;
                            listTemp.addAll(listTempXX);
                            number = number + listTempXX.size();
                        }
                    }
                }
            }
            for (RemoveUserAndAddress item : list1) {
                List<OrderExport> list2 = listTempOther.stream().filter(c -> (
//                                    c.getUserId()!=null&&c.getUserId().equals(item.getUserId())&&
                                c.getLogname() != null && c.getLogname().equals(item.getLogname()) &&
                                        c.getPhone() != null && c.getPhone().equals(item.getPhone()) &&
                                        c.getAddressAll() != null && c.getAddressAll().equals(item.getAddressAll()))
                ).collect(Collectors.toList());
                Collections.sort(list2, Comparator.comparingInt(OrderExport::getProductCount));//根据数量排序
                List<OrderExport> listTemp1 = new ArrayList<>();
                if (list2 != null && list2.size() > 0) {
                    listTemp1 = exportService.assOrderData(list2);
                }

                //再次进行组合
                if (list2 != null && list2.size() > 0) {
                    if(listTemp1!=null&&listTemp1.size()>0){
                        listTemp.addAll(listTemp1);
                        number = number + listTemp1.size();
                    }
                }
            }

        }catch(Exception e){
            up = 1;
        }
        //组合数据添加到Excel
        if(listTemp!=null&&listTemp.size()>0){
            Collections.sort(listTemp, Comparator.comparing(OrderExport::getLogname));//排序
        }

        String [][] content=new String[listTemp.size()][];
//
//        if(listTemp.size()<=0){
//            content=new String[1][];
//            content[0] = new String[title.length];
//            if(error.equals("")){
//                content[0][0] = "空空如也!";content[0][1] = "空空如也!";content[0][2] = "空空如也!";content[0][3] = "空空如也!";
//                content[0][4] = "空空如也!";content[0][5] = "空空如也!";content[0][6] = "空空如也!";
//            }else {
//                content[0][0] = error;
//            }
//        }
//        for (int i = 0; i < listTemp.size(); i++){
//            OrderExport orderExport=listTemp.get(i);
//            content[i] = new String[title.length];
//            content[i][0] = busidstr+"-"+(i+1);//业务单号
//            content[i][1] = orderExport.getLogname();
//            content[i][2] = orderExport.getPhone();
//            content[i][3] = orderExport.getAddressAll();
//            content[i][4] = orderExport.getGuigeName();
//            content[i][5] = "";
//            content[i][6] = orderExport.getSupplier();
//            content[i][7] =orderExport.getOrderNo();
//        }
        //创建HSSFWorkbook
        listSupplier.add(suname);
        List<String> listSup1 = new ArrayList<>(listSupplier);
        listSup1.remove(suname);
        List<String> ss=new ArrayList<>();
        ss.add(suname);
        ss.addAll(listSup1);
        List<File> wb = ExcelUtil.getHSSFWorkbookZip(sheetName, title, content, null,ss,listTemp);
        String url="";
        String zipUrl="";
        try {
            String path="/usr/local/mall_uploads/logistics";
            //String path="D:/logzip";
            File uploadPath=new File(path);
            if(!uploadPath.exists()){
                uploadPath.mkdirs();
            }
            zipUrl="HSYS"+System.currentTimeMillis()+".zip";
            url="/logistics/"+zipUrl;
            FileOutputStream fos2 = new FileOutputStream(uploadPath+"/"+zipUrl);
            toZip(wb,fos2);

            try {
                setResponseHeader(response,zipUrl);
                OutputStream os = response.getOutputStream();
                FileInputStream fis = new FileInputStream(uploadPath+"/"+zipUrl);
                int n = 0;
                byte[] buff = new byte[1024];
                while ((n = fis.read(buff)) != -1) {
                    os.write(buff, 0, n);
                }
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
//        //
//        String url="";
//        //保存excel
//        try {
//            String path="/usr/local/mall_uploads/logistics";
//            File uploadPath=new File(path);
//            if(!uploadPath.exists()){
//                uploadPath.mkdirs();
//            }
//            FileOutputStream fileOut = new FileOutputStream(uploadPath+"/"+fileName);
//            url="/logistics/"+fileName;
//            wb.write(fileOut);
//            fileOut.close();
//        }
//        catch (Exception e){
//            e.printStackTrace();
//            up=1;
//        }
        //响应到客户端
//        ZipOutputStream zos = null ;
//        try {
//            setResponseHeader(response,zipUrl);
//            OutputStream os = response.getOutputStream();
//            zos.write(os);
//            os.flush();
//            os.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        if(up==0){
            //更新为导单状态
            List lists=null;
            try {
                Object[] list1X=hashSet.toArray();
                String[] stringArray = Arrays.copyOf(list1X, list1X.length, String[].class);
                lists = java.util.Arrays.asList(stringArray);
            }catch (Exception e){}

            if(lists!=null&&lists.size()>0){
                HttpSession session=request.getSession();
                Integer adminid= (Integer) session.getAttribute("adminId");
                String orderNos=hashSet.toString().trim().replace('[','(').replace(']',')');

                int res=orderService.upOrderFrom(lists,new Date());
                ExportOrder exportOrder=new ExportOrder();
                exportOrder.setNumber(number);
                exportOrder.setType(1);
                exportOrder.setTypename("快递");
                exportOrder.setUrl(url);
                exportOrder.setTime(new Date());
                exportOrder.setOrdernos(orderNos);
                exportOrder.setAdminuserid(adminid);
                int res1=exportOrderService.insertSelective(exportOrder);
            }
        }
    }

    @Override
    public void exportExcel() {
        List<RemoveUserAndAddress> listOther=new ArrayList<>();//存放去重的用户收货信息
        List<OrderExport> listEx1 = orderExportService.getOrderExportData1();//
        List<OrderExport> list = listEx1;//导单数据
        List<OrderExport> listTemp=new ArrayList<>();//特殊产品
        List<OrderExport> listTempOther=new ArrayList<>();//特殊以外的其他产品数据
        List<OrderExport> listTempSupplier=new ArrayList<>();//供货商产品数据
        List<DemolitionOrder> demolitionOrders=demolitionOrderService.selectAll();//需要进行拆单的基础数据
        HashSet<String> hashSet=new HashSet<>();//订单编号
        int number=0;//导单数量
        int up=0;
        String[] title = {"业务单号","收件人姓名","收件人手机","收件人地址","品名","数量","备注","订单号"};
        String fileName = "物流导单"+System.currentTimeMillis()+".xls";
        DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        String busidstr = format2.format(new Date());
        String sheetName = "HSYS"+busidstr;
        OrderExport errorOO=new OrderExport();
        Set<String> listSupplier=new HashSet<>();
        String supName="";
        String suname="贵州荟生生物科技有限公司";
        try {
            for (int i = 0; i < list.size(); i++) {
                OrderExport orderExport = list.get(i);
                String supplier = orderExport.getSupplier() == null ? "" : orderExport.getSupplier();
                if ("".equals(supplier)) {
                    supName = "未知";
                } else {
                    supName = supplier;
                }
                if(!supName.equals(suname)){
                    listSupplier.add(supName);
                }
                errorOO = list.get(i);
                String[] strings = orderExport.getOrderNo().split(",");
                if (strings.length == 1) {
                    hashSet.add(orderExport.getOrderNo());
                } else {
                    for (String str : strings) {
                        hashSet.add(str);
                    }
                }
                //获取所有用户收货信息
                RemoveUserAndAddress orderExport1 = new RemoveUserAndAddress();
//                orderExport1.setUserId(orderExport.getUserId());
                orderExport1.setLogname(orderExport.getLogname());
                orderExport1.setPhone(orderExport.getPhone());
                orderExport1.setAddressAll(orderExport.getAddressAll());
                String name = list.get(i).getGuigeName1();
                //orderExport1.setAddressId(orderExport.getAddressId());
                listOther.add(orderExport1);
                //获取所有用户收货信息结束
                int productId = 0, guigeId = 0, productCount = 0;
                productId = list.get(i).getProductId();
                guigeId = list.get(i).getGuigeId();
                productCount = list.get(i).getProductCount();
                //判断产品大于一定数量是否拆单
                int finalProductId = productId;
                int finalGuigeId = guigeId;
                //判断产品大于一定数量是否拆单
                boolean isChai = demolitionOrders.stream().anyMatch(str -> (finalProductId == str.getProductid() && finalGuigeId == str.getGuigeid() && str.getType() == 1));
                boolean isChai1 = demolitionOrders.stream().anyMatch(str -> (finalProductId == str.getProductid() && finalGuigeId == str.getGuigeid() && str.getType() == 2));
                if (!suname.equals(supName)) {
                    listTempSupplier.add(orderExport);
                } else if (isChai) {//类型为1拆单
                    for (int n = 0; n < productCount; n++) {
                        OrderExport orderExportTemp = orderExport;
                        orderExportTemp.setGuigeName(name + "*" + 1);
                        listTemp.add(orderExportTemp);
                        number++;
                    }
                } else if (isChai1) {//类型为2拆单
                    int c = productCount / 6;// a-(a/b)*b
                    if (c == 1) {//单瓶整除为1
                        OrderExport orderExportTemp = exportService.orderGroup(orderExport);
                        orderExportTemp.setGuigeName(name + "*" + 6);
                        listTemp.add(orderExportTemp);
                        number++;
                    }
                    if (c > 1) {//单瓶整除大于1
                        for (int n = 0; n < c; n++) {
                            OrderExport orderExportTemp = exportService.orderGroup(orderExport);
                            orderExportTemp.setGuigeName(name + "*" + 6);
                            listTemp.add(orderExportTemp);
                            number++;
                        }
                    }
                    if (productCount % 6 != 0) {//处理剩下不到一件的
                        int d = productCount - (productCount / 6) * 6;
                        OrderExport orderExportTemp = exportService.orderGroup(orderExport);
                        orderExportTemp.setGuigeName(name + "*" + d);
                        listTemp.add(orderExportTemp);
                        number++;
                    }
                } else {
                    //添加到特殊产品拆单以外的其它集合
                    listTempOther.add(orderExport);
                }
            }
            //根据用户合并其它产品
            //去除用户重复的收货信息
            List<RemoveUserAndAddress> list1 = exportService.removeDuplicate(listOther);

            //根据去重的用户收货信息进行整合特殊以外产品信息
            List<OrderExport> listTempXX = new ArrayList<>();
            for (String str : listSupplier) {
                for (RemoveUserAndAddress item : list1) {
                    List<OrderExport> list2 = listTempSupplier.stream().filter(c -> (
                            c.getLogname() != null && c.getLogname().equals(item.getLogname()) &&
                                    c.getPhone() != null && c.getPhone().equals(item.getPhone()) &&
                                    c.getAddressAll() != null && c.getAddressAll().equals(item.getAddressAll()))
                    ).collect(Collectors.toList());
                    Collections.sort(list2, Comparator.comparingInt(OrderExport::getProductCount));//根据数量排序
                    if (list2 != null && list2.size() > 0) {
                        listTempXX = exportService.assOrderDataName(list2,str);
                    }
                    if (list2 != null && list2.size() > 0) {
                        if(listTempXX!=null&&listTempXX.size()>0){
                            List<OrderExport> list1q=listTempXX.stream().filter(c -> (!c.getOrderNo().equals("null")&&!c.getOrderNo().equals("")))
                                    .collect(Collectors.toList());
                            listTempXX=list1q;
                            listTemp.addAll(listTempXX);
                            number = number + listTempXX.size();
                        }
                    }
                }
            }
            for (RemoveUserAndAddress item : list1) {
                List<OrderExport> list2 = listTempOther.stream().filter(c -> (
//                                    c.getUserId()!=null&&c.getUserId().equals(item.getUserId())&&
                                c.getLogname() != null && c.getLogname().equals(item.getLogname()) &&
                                        c.getPhone() != null && c.getPhone().equals(item.getPhone()) &&
                                        c.getAddressAll() != null && c.getAddressAll().equals(item.getAddressAll()))
                ).collect(Collectors.toList());
                Collections.sort(list2, Comparator.comparingInt(OrderExport::getProductCount));//根据数量排序
                List<OrderExport> listTemp1 = new ArrayList<>();
                if (list2 != null && list2.size() > 0) {
                    listTemp1 = exportService.assOrderData(list2);
                }

                //再次进行组合
                if (list2 != null && list2.size() > 0) {
                    if(listTemp1!=null&&listTemp1.size()>0){
                        listTemp.addAll(listTemp1);
                        number = number + listTemp1.size();
                    }
                }
            }

        }catch(Exception e){
            up = 1;
        }
        //组合数据添加到Excel
        if(listTemp!=null&&listTemp.size()>0){
            Collections.sort(listTemp, Comparator.comparing(OrderExport::getLogname));//排序
        }

        String [][] content=new String[listTemp.size()][];
//
//        if(listTemp.size()<=0){
//            content=new String[1][];
//            content[0] = new String[title.length];
//            if(error.equals("")){
//                content[0][0] = "空空如也!";content[0][1] = "空空如也!";content[0][2] = "空空如也!";content[0][3] = "空空如也!";
//                content[0][4] = "空空如也!";content[0][5] = "空空如也!";content[0][6] = "空空如也!";
//            }else {
//                content[0][0] = error;
//            }
//        }
//        for (int i = 0; i < listTemp.size(); i++){
//            OrderExport orderExport=listTemp.get(i);
//            content[i] = new String[title.length];
//            content[i][0] = busidstr+"-"+(i+1);//业务单号
//            content[i][1] = orderExport.getLogname();
//            content[i][2] = orderExport.getPhone();
//            content[i][3] = orderExport.getAddressAll();
//            content[i][4] = orderExport.getGuigeName();
//            content[i][5] = "";
//            content[i][6] = orderExport.getSupplier();
//            content[i][7] =orderExport.getOrderNo();
//        }
        //创建HSSFWorkbook
        listSupplier.add(suname);
        List<String> listSup1 = new ArrayList<>(listSupplier);
        listSup1.remove(suname);
        List<String> ss=new ArrayList<>();
        ss.add(suname);
        ss.addAll(listSup1);
        List<File> wb = ExcelUtil.getHSSFWorkbookZip(sheetName, title, content, null,ss,listTemp);
        String url="";
        String zipUrl="";
        try {
            String path="/usr/local/mall_uploads/logistics";
            //String path="D:/logzip";
            File uploadPath=new File(path);
            if(!uploadPath.exists()){
                uploadPath.mkdirs();
            }
            zipUrl="HSYS"+System.currentTimeMillis()+".zip";
            url="/logistics/"+zipUrl;
            FileOutputStream fos2 = new FileOutputStream(uploadPath+"/"+zipUrl);
            toZip(wb,fos2);

//            try {
//                setResponseHeader(response,zipUrl);
//                OutputStream os = response.getOutputStream();
//                FileInputStream fis = new FileInputStream(uploadPath+"/"+zipUrl);
//                int n = 0;
//                byte[] buff = new byte[1024];
//                while ((n = fis.read(buff)) != -1) {
//                    os.write(buff, 0, n);
//                }
//                os.flush();
//                os.close();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
//        //
//        String url="";
//        //保存excel
//        try {
//            String path="/usr/local/mall_uploads/logistics";
//            File uploadPath=new File(path);
//            if(!uploadPath.exists()){
//                uploadPath.mkdirs();
//            }
//            FileOutputStream fileOut = new FileOutputStream(uploadPath+"/"+fileName);
//            url="/logistics/"+fileName;
//            wb.write(fileOut);
//            fileOut.close();
//        }
//        catch (Exception e){
//            e.printStackTrace();
//            up=1;
//        }
        //响应到客户端
//        ZipOutputStream zos = null ;
//        try {
//            setResponseHeader(response,zipUrl);
//            OutputStream os = response.getOutputStream();
//            zos.write(os);
//            os.flush();
//            os.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        if(up==0){
            //更新为导单状态
            List lists=null;
            try {
                Object[] list1X=hashSet.toArray();
                String[] stringArray = Arrays.copyOf(list1X, list1X.length, String[].class);
                lists = java.util.Arrays.asList(stringArray);
            }catch (Exception e){}

            if(lists!=null&&lists.size()>0){
                String orderNos=hashSet.toString().trim().replace('[','(').replace(']',')');
                int res=orderService.upOrderFrom(lists,new Date());
                ExportOrder exportOrder=new ExportOrder();
                exportOrder.setNumber(number);
                exportOrder.setType(1);
                exportOrder.setTypename("快递");
                exportOrder.setUrl(url);
                exportOrder.setTime(new Date());
                exportOrder.setOrdernos(orderNos);
                exportOrder.setAdminuserid(10);
                int res1=exportOrderService.insertSelective(exportOrder);
            }
        }
    }
}
